<?php

/**
 * See if a user is actualy logged in or not
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_is_logged_in(){
	$user= blg_get_logged_in_user_guid();
	return ($user!==FALSE);	
}


/**
 * Get logged in user GUID
 * @return int User's GUID
 * @author Pablo
 * @since 1.0
 */
function blg_get_logged_in_user_guid(){
	$user_guid= blg_session_get('login_user');
	
	if(empty($user_guid))
		return FALSE;
		
	return $user_guid;
}

/**
 * Get logged in user entity
 * @return BlgUser User entity or FALSE if no user is logged
 * @author Pablo
 * @since 1.0
 */
function blg_get_logged_in_user_entity(){
	$user_guid= blg_session_get('login_user');
	
	if(empty($user_guid))
		return FALSE;
		
	return new BlgUser($user_guid);
}

/**
 * Logout logged in user
 * @author Pablo
 * @since 1.0
 */
function blg_logout(){
	blg_session_unset('login_user');	
}

/**
 * Log in a user
 * @param $guid User's GUID
 * @author Pablo
 * @since 1.0
 */
function blg_login($guid){
	blg_logout();
	blg_session_set('login_user', $guid);
}

/**
 * Tells if a user is an administrator
 * @param unknown_type $user_guid
 */
function blg_user_is_admin($user_guid){
	$user= blg_get_user_entity($user_guid);
	return ($user->admin=='yes');
}

/**
 * Tells if a username exists or not
 * @param $username
 * @return boolean
 * @author Pablo
 * @since 1.0
 */
function blg_username_exists($username, $enabled= NULL){
	$query= blg_dbschema_select_users(array('username' => $username, 'enabled' => $enabled));
	$query= blg_dbschema_query_buid($query, 'count');
	$result= blg_dbschema_select($query);
	$result= (int)$result->{0}['result'];
	return ($result>0);
}

/**
 * Tells if a user email exists or not
 * @param $username
 * @return boolean
 * @author Pablo
 * @since 1.0
 */
function blg_email_exists($email){
	$query= blg_dbschema_select_users(array('email' => $email));
	$query= blg_dbschema_query_buid($query, 'count');
	$result= blg_dbschema_select($query);
	$result= (int)$result->{0}['result'];
	return ($result>0);
}

/**
 * Tells if a user email exists or not
 * @param $username
 * @return boolean
 * @author Pablo
 * @since 1.0
 */
function blg_usercode_exists($usercode){
	$query= blg_dbschema_select_users(array('code' => $usercode));
	$query= blg_dbschema_query_buid($query, 'count');
	$result= blg_dbschema_select($query);
	$result= (int)$result->{0}['result'];
	return ($result>0);
}

/**
 * Create a new user
 * 
 * @param string $name
 * @param string $username
 * @param string $password1
 * @param string $password2 
 * @param string $email
 * @return The new user GUID, or FALSE in case of failure
 * @author Pablo
 * @since 1.0
 */
function blg_new_user($name, $username, $email, $password1, $password2){
	if(v_blg_new_user($name, $username, $email, $password1, $password2)){
		blg_TRANSACTION();
		
		$salt= random_string(8);
		$time= time();
		
		//INSERT entity row
		$query= blg_dbschema_query_buid(blg_dbschema_insert_entity(array(
			'type' => 'user',
			'owner_guid' => blg_get_config('site_guid'),
			'site_guid' => blg_get_config('site_guid'),
			'container_guid' => blg_get_config('site_guid'),
			'access_id' => ACCESS_DEFAULT,
			'time_created' => $time,
			'time_updated' => 0,
			'last_action' => 0,
			'enabled' => 'yes' 	
		)));
		$result= blg_dbschema_insert($query);
		$user_guid= $result->new_id;
	
		if($result->success){
			//INSERT user row
			$query= blg_dbschema_query_buid(blg_dbschema_insert_user(array(
				'guid' => $user_guid,
				'name' => $name,
				'surname' => '',
				'username' => $username,
				'password' => md5(SALT.$password1.$salt),
				'salt' => $salt,
				'email' => $email,
				'language' => blg_get_config('language'),
				'code' => random_string(32),
				'banned' => 'validation',
				'admin' => 'no',
				'prev_last_action' => 0,
				'last_login' => 0,
				'prev_last_login' => 0
			)));
			$result= blg_dbschema_insert($query);
			if($result->success){
				blg_COMMIT();
				return $user_guid;
			}
		}		
	}		
	
	blg_ROLLBACK();
	return FALSE;	
}

/**
 * Get user from GUID
 * @param $user_guid
 * @return BlgUser User entity object
 * @author Pablo
 * @since 1.0
 */
function blg_get_user_entity($user_guid, $strict= TRUE){
	try {
	    $user= new BlgUser($user_guid);
	    return $user;
	} catch( Exception $e ) {
	    blg_log($e->getMessage(), $strict, $strict);
	}
}

/**
 * Get user from email
 * @param $email
 * @return (Array|NULL) User entity or NULL in case of failure
 * @author Pablo
 * @since 1.0
 */
function blg_get_user_entity_by_email($email, $strict= TRUE){
	try {
	    $user= new BlgUser($email, 'email');
	    return $user;
	} catch( Exception $e ) {
	    blg_log($e->getMessage(), $strict, $strict);
	}
}

/**
 * Get user from username
 * @param $username
 * @return Array User
 * @author Pablo
 * @since 1.0
 */
function blg_get_user_entity_by_username($username, $strict= TRUE){
	try {
	    $user= new BlgUser($username, 'username');
	    return $user;
	} catch( Exception $e ) {
	    blg_log($e->getMessage(), $strict, $strict);
	}
}

/**
 * Get user from username
 * @param $username
 * @return Array User
 * @author Pablo
 * @since 1.0
 */
function blg_get_user_entity_by_code($usercode, $strict= TRUE){
	try {
	    $user= new BlgUser($usercode, 'code');
	    return $user;
	} catch( Exception $e ) {
	    blg_log($e->getMessage(), $strict, $strict);
	}
}

/**
 * Deletes a user
 * Actually, it disables user entity
 * 
 * @param $guid User GUID
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_delete_user($guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_entities(
		array('guid' => $guid),
		array('enabled' => 'no')
	));
	$result= blg_dbschema_update($query);
	return ($result->success && $result->affected_rows>0 );
}

/**
 * Ban a user
 *
 * @param $guid User GUID
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_ban_user($guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('banned' => 'yes')
	));
	$result= blg_dbschema_update($query);
	return $result->success;	
}

/**
 * Unban a user
 *
 * @param $guid User GUID
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_unban_user($guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('banned' => 'no')
	));
	$result= blg_dbschema_update($query);
	return $result->success;	
}

/**
 * Activate a user
 *
 * @param $guid User GUID
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_activate_user($guid){
	return blg_unban_user($guid);
}

/**
 * Make a user administrator
 *
 * @param int $guid User GUID  
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_make_admin($guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('admin' => 'yes')
	));
	$result= blg_dbschema_update($query);
	return $result->success;	
}

/**
 * Revoke a user administrator perms
 *
 * @param int $guid User GUID  
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_revoke_admin($guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('admin' => 'no')
	));
	$result= blg_dbschema_update($query);
	return $result->success;	
}

/**
 * Update user last login times
 * @param $guid User GUID
 * @param $time
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_last_login($guid, $time=NULL){
	if(empty($time))
		$time= time();
	
	//Select actual time
	$result= blg_dbschema_select(blg_dbschema_query_buid(blg_dbschema_select_users(
		array('guid' => $guid),
		array('last_login')
	)));
	$last_login= (int)$result->{0}['last_login'];	
		
	//Update
	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('prev_last_login' => $last_login, 'last_login' => $time)
	));
	$result= blg_dbschema_update($query);
		
	return $result->success;
}

/**
 * Update user previous last action time
 * @param $guid User GUID
 * @param $time
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_prev_last_action($guid, $time=NULL){
	if(empty($time))
		$time= time();

	$query= blg_dbschema_query_buid(blg_dbschema_update_users(
		array('guid' => $guid),
		array('prev_last_action' => $time)
	));
	$result= blg_dbschema_update($query);
	return $result->success;
}

/**
 * Update user last action times
 * 
 * @param $guid
 * @param $time
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_last_action($guid, $time=NULL){
	if(empty($time))
		$time= time();
			
	blg_TRANSACTION();
	$prev_last_action= blg_entity_last_action($guid, $time);
	$result= blg_user_prev_last_action($guid, $prev_last_action);
	
	if($prev_last_action===FALSE || $result===FALSE){
		blg_ROLLBACK();
		return FALSE;
	}
		
	blg_COMMIT();
	return TRUE;			
}

/**
 * Verify user password
 * @param $guid
 * @param $password
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_user_check_password($guid, $password){
	$user= blg_get_user_entity($guid);	
	
	return(md5(SALT.$password.$user['salt']) == $user['password']);
}

/**
 * Login a user
 * @param $email
 * @param $password
 * @author Pablo
 * @since 1.0
 */
function blg_user_do_login($email, $password){
	$user= blg_get_user_entity_by_email($email);

	if(!empty($user)){
		if(blg_user_check_password($user['guid'], $password)){	
			$time= time();
				
			if(!blg_user_last_login($user['guid'], $time))
				blg_log('Could not update last LOGIN time for user GUID'.$user['guid']);
			
			if(!blg_user_last_action($user['guid'], $time))
				blg_log('Could not update last ACTION time for user GUID'.$user['guid']);
			
			blg_login($user['guid']);				
			return TRUE;
		}
	}
	
	return FALSE;
}


/**
 * Obtain a user's validation code
 * @param mixed $user_or_userguid
 * @return String The code
 * @author Pablo
 * @since 1.0
 */
function blg_user_get_validation_code($user_or_userguid){
	if($user_or_userguid instanceof BlgUser){
		return md5(SALT_VALIDATION.($user_or_userguid->code));
	}
	else{
		$user= blg_get_user_entity($user_or_userguid);
		return md5(SALT_VALIDATION.($user->code));
	}

	return FALSE;
}


/******************************************
 * 			SEND EMAILS TO USER
 *****************************************/

/**
 * Sends an email to a NEW registed user with the validation code
 * @param int $user_guid
 * @author Pablo
 * @since 1.0
 */
function blg_user_send_registrarion_email($user_guid){
	$site= blg_get_site_entity();
	$user= blg_get_user_entity($user_guid);
	$email_content= implode("<br>\n", array(
		blg_echo('register:email:register', array($site->name)),
		blg_echo('register:valdiate:str1', array($user->email)),
		blg_echo('register:valdiate:str2'),
		blg_echo('register:valdiate:str3', array($user->getValidationURL(), $user->getValidationURL())),
	));
	$email_body= blg_view('layout/email', array(
		'addressee_guid' 	=> $user_guid,
		'content'			=> $email_content,
		'site'				=> $site
	));
	blg_send_email($user->email, blg_echo('register:email:subject', array($site->name)), $email_body);	
}

/**
 * Sends an email to a ALREADY registed user with the validation code
 * @param int $user_guid
 * @author Pablo
 * @since 1.0
 */
function blg_user_send_validation_email($user_guid){
	$site= blg_get_site_entity();
	$user= blg_get_user_entity($user_guid);
	$email_content= implode("<br/>\n", array(
		blg_echo('register:confirm1', array($user->email)),
		blg_echo('register:valdiate:str2'),
		blg_echo('register:valdiate:str3', array($user->getValidationURL(), $user->getValidationURL())),
	));
	$email_body= blg_view('layout/email', array(
		'addressee_guid' 	=> $user_guid,
		'content'			=> $email_content,
		'site'				=> $site
	));
	blg_send_email($user->email, blg_echo('register:email:subject', array($site->name)), $email_body);	
}

/**
 * Sends an email to CONFIRM new password REQUEST
 * @param int $user_guid
 * @author Pablo
 * @since 1.0
 */
function blg_user_send_confirm_reset_password_email($user_guid){
	$site= blg_get_site_entity();
	$user= blg_get_user_entity($user_guid);
	$email_content= implode("<br/>\n", array(
		blg_echo('forms:password:reset:email:body:1'),
		blg_echo('forms:password:reset:email:body:2'),
		'<br/>'.blg_echo('forms:password:reset:email:body:3', array($user->getResetPasswordURL(), $user->getResetPasswordURL())),
		'<br/>'.blg_echo('forms:password:reset:email:body:4')
	));
	$email_body= blg_view('layout/email', array(
		'addressee_guid' 	=> $user_guid,
		'content'			=> $email_content,
		'site'				=> $site
	));
	blg_send_email($user->email, blg_echo('forms:password:reset:email:subject'), $email_body);	
}

/**
 * Sends an email to CONFIRM new password CHANGED
 * @param int $user_guid
 * @author Pablo
 * @since 1.0
 */
function blg_user_send_reset_password_email($user_guid, $new_password){
	$site= blg_get_site_entity();
	$user= blg_get_user_entity($user_guid);
	$email_content= implode("<br/>\n", array(
		blg_echo('user:password:reset:done:email:body:1'),
		blg_echo('user:password:reset:done:email:body:2', array($new_password))
	));
	$email_body= blg_view('layout/email', array(
		'addressee_guid' 	=> $user_guid,
		'content'			=> $email_content,
		'site'				=> $site
	));
	blg_send_email($user->email, blg_echo('user:password:reset:done:email:subject'), $email_body);	
}












